package com.xyf.sys.util;

import com.sf.csim.express.service.CallExpressServiceTools;
import com.sf.csim.express.service.HttpClientUtil;
import com.xyf.sys.config.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


/**
 *
 */
@Slf4j
public class CallExpressSFHttpUtil {

    private static String CLIENT_CODE = "BTQZYNDVFS30";
    private static String CHECK_WORD = "3bd2WHMbE3i0157ToFB0zj87JMdSpAjZ";
//    private static String CHECK_WORD = "wrIhwVLlrr5vLjx4xEwTr5AbSDNCDGmw";
//    private static String CALL_URL_BOX = "https://sfapi-sbox.sf-express.com/std/service";
    private static String CALL_URL_PROD = "https://bspgw.sf-express.com/std/service";

    /**
     * @Description: 调用顺丰API方法
     * msgData：请求报文  serviceCode:接口服务码
     * @Date: 2023/3/20 17:25
     **/
    public static String callSFApi(String serviceCode, String msgData) throws UnsupportedEncodingException {
        //验证请求参数
        if (StringUtils.isEmpty(serviceCode) || StringUtils.isEmpty(msgData)) {
            throw new CustomException("参数不能为空!");
        }
        CallExpressServiceTools tools = CallExpressServiceTools.getInstance();
        Map<String, String> params = new HashMap<>(8);
        String timeStamp = String.valueOf(System.currentTimeMillis());

        params.put("partnerID", CLIENT_CODE);  // 顾客编码 ，对应丰桥上获取的clientCode
        params.put("requestID", UUID.randomUUID().toString().replace("-", ""));//请求唯一号UUID
        params.put("serviceCode", serviceCode);// 接口服务码
        params.put("timestamp", timeStamp);//调用接口时间戳
        params.put("msgData", msgData);//报文
        params.put("msgDigest", tools.getMsgDigest(msgData, timeStamp, CHECK_WORD));//数字签名
        long startTime = System.currentTimeMillis();
        log.info("====调用实际请求：" + params);
        String result = HttpClientUtil.post(CALL_URL_PROD, params);
        log.info("====调用丰桥的接口服务代码：" + String.valueOf(serviceCode) + " 接口耗时：" + String.valueOf(System.currentTimeMillis() - startTime) + "====");
        log.info("===调用地址 ===" + CALL_URL_PROD);
        log.info("===顾客编码 ===" + CLIENT_CODE);
        log.info("===返回结果：" + result);
        return result;
    }

}